package com.mucd.chat.utils;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * session容器
 */
@Slf4j
public class SessionContainer {

    private static final Map<String, Session> SESSION_KEY = new ConcurrentHashMap<>();

    /**
     * 添加session
     *
     * @param key     key
     * @param session session
     */
    public static void put(String key, Session session) {
        SESSION_KEY.put(key, session);
    }

    /**
     * 获取session
     *
     * @param key key
     * @return session
     */
    public static Session get(String key) {
        return SESSION_KEY.get(key);
    }

    public static void deleteByKey(String key) {
        Session session = SESSION_KEY.remove(key);

        if (session.isOpen()) {
            try {
                session.close();
            } catch (IOException e) {
                log.error("关闭session失败", e);
            }
        }
    }
}
